package com.dg.gaming.tictactoe.gui {
    import com.dg.gaming.client.gui.GameController;
    import com.dg.gaming.tictactoe.common.MsgTicTacToeMove;
    import com.dg.gaming.tictactoe.common.TicTacToeModel;

    import flash.events.MouseEvent;
    import flash.geom.Point;

    public class TicTacToeController extends GameController {
        // links to game data and the board component
        protected var tmodel:TicTacToeModel;

        protected var boardComponent:TicTacToeBoardComponent;



        public function TicTacToeController(model:TicTacToeModel, component:TicTacToeBoardComponent) {
            super(model, component);

            this.tmodel = model; // set fields
            this.boardComponent = component;

        }

        // Start method which calls reset method (resets the model).
        public override function start():void {
            tmodel.reset();
        }

        /**
         * Invoked when a mouse button has been pressed on a DGComponent.
         *
         * @param e
         */
        public override function mousePressed(evnt:MouseEvent):void {
            if (isGamePlaying() && isThisPlayersTurn()) { // ensure game has started
                var board:Point = boardComponent.getBoardCoords(evnt.localX, evnt.localY);
                if (board.x >= 0 && board.x < 3 && board.y >= 0 && board.y < 3) {
                    // check model at this point is BLANK and it is this persons go
                    if (tmodel.getData(board.x, board.y) == TicTacToeModel.BLANK) {
                        moveData(board.x, board.y);
                    }
                }
            }
        }

        public function moveData(x:int, y:int):void {
            // update model and change player turn
            var value:int = getCurrentPlayerSeatNum();
            tmodel.setData(x, y, value);
            // send move to other user
            var move:MsgTicTacToeMove = new MsgTicTacToeMove(x, y, value);
            // next player turn.
            nextPlayer(move);

        }

    }
}